﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace App.Utils
{
    public static class HttpHelper
    {
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">key value自动拼装在连接在url后面</param>
        /// <param name="contentType">内容类型：application/json,application/xml</param>
        /// <returns></returns>
        public static Result<string> HttpGet(string url, Dictionary<string, string> param, ContentType contentType = ContentType.Json)
        {
            return HttpGet(url, param, null, contentType);
        }

        public static Result<string> HttpGet(string url, Dictionary<string, string> param, Dictionary<string, string> headers, ContentType contentType = ContentType.Json)
        {
            try
            {
                string retString = string.Empty;
                if (param != null && param.Count > 0)
                {
                    url += "?";
                    foreach (KeyValuePair<string, string> kvp in param)
                        url += $"{kvp.Key}={kvp.Value}&";
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = GetContentTypeStr(contentType);

                if (headers != null && headers.Count > 0)
                {
                    foreach (KeyValuePair<string, string> kvp in headers)
                        request.Headers.Add(kvp.Key, kvp.Value);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(myResponseStream);
                retString = streamReader.ReadToEnd();
                streamReader.Close();
                myResponseStream.Close();
                return new Result<string>() { Data = retString };
            }
            catch (Exception ex)
            {
                return new Result<string>() { Code = ResultCode.Error, Msg = ex.Message };
            }
        }


        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">访问地址</param>
        /// <param name="postDataStr">body字符</param>
        /// <param name="contentType">内容类型：application/json,application/xml</param>
        /// <param name="isOK">是否成功</param>
        /// <returns></returns>
        public static Result<string> HttpPost(string url, string postDataStr, ContentType contentType = ContentType.Json)
        {
            string retString = string.Empty;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = GetContentTypeStr(contentType);
                request.Timeout = 600000;//设置超时时间
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                Stream requestStream = request.GetRequestStream();
                StreamWriter streamWriter = new StreamWriter(requestStream);
                streamWriter.Write(postDataStr);
                streamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream responseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream);
                retString = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();

                return new Result<string>() { Data = retString };
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(WebException))//捕获400错误
                {
                    var response = ((WebException)ex).Response;
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream);
                    retString = streamReader.ReadToEnd();
                    streamReader.Close();
                    responseStream.Close();
                }
                else
                {
                    retString = ex.ToString();
                }
                return new Result<string>() { Code = ResultCode.Error, Data = retString };
            }

        }

        public static string GetContentTypeStr(ContentType contentType)
        {
            switch (contentType)
            {
                case ContentType.Json:
                    return "application/json";
                case ContentType.Xml:
                    return "application/xml";
                case ContentType.FormUrlencoded:
                    return "application/x-www-form-urlencoded";
                default:
                    return "";
            }
        }
    }

    public enum ContentType
    {
        Json,
        Xml,
        FormUrlencoded

    }
}